package com.situ.allaia.api;

import com.situ.allaia.model.AdminUser;
import com.situ.allaia.model.AdminUserSearchBean;
import com.situ.allaia.service.AdminUserService;
import com.situ.allaia.util.PaginateInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/admin_users",produces = "application/json;charset=utf-8")
public class AdminUserApi {
    private final AdminUserService adminUserService;

    public AdminUserApi(AdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }

    @GetMapping
    public Map<String,Object> findAll(AdminUserSearchBean asb,
                                      @RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10")Integer limit){
        PaginateInfo pi = new PaginateInfo(page,limit);
        List<AdminUser> adminUserList = adminUserService.findAll(asb,pi);
//        System.out.println(adminUserList);
        return Map.of("code",0,"msg","",
                "count",pi.getTotal(),"data",adminUserList);
    }

    @PostMapping
    public Map<String,Object> save(AdminUser adminUser){
        //参数校验
        if (!StringUtils.hasText(adminUser.getUsername())){
            return Map.of("success",false,"error","用户名不允许为空");
        }
        if (!StringUtils.hasText(adminUser.getPassword())){
            return  Map.of("success",false,"error","密码不允许为空");
        }
        boolean success = adminUserService.save(adminUser);
        if (success){
            return Map.of("success",true,"data",adminUser);
        }else{
            return Map.of("success",false,"error","修改后台用户失败");
        }
    }
    @PutMapping
    public Map<String,Object> edit(AdminUser adminUser){
        //参数校验
        if (!StringUtils.hasText(adminUser.getUsername())){
            return Map.of("success",false,"error","用户名不允许为空");
        }
        if (!StringUtils.hasText(adminUser.getPassword())){
            return  Map.of("success",false,"error","密码不允许为空");
        }
        boolean success = adminUserService.update(adminUser);
        if (success){
            return Map.of("success",true,"data",adminUser);
        }else{
            return Map.of("success",false,"error","修改信息失败");
        }
    }
    @DeleteMapping
    public Map<String,Object> deleteBiIds(Integer[] ids){
        //参数校验
        if (ids==null||ids.length ==0){
            return Map.of("success",false,"error","未选中要删除的数据");
        }
        int rows = adminUserService.deleteByIds(ids);
        if (rows > 0){
            return Map.of("success",true,"rows",rows);
        }else {
            return Map.of("success",false,"error","未删除任何记录");
        }
    }
}
